package com.jerry.walking.module.activityPage.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jerry.walking.R;
import com.jerry.walking.base.BaseFragment;
import com.jerry.walking.constant.Urls;
import com.jerry.walking.module.activityPage.adapter.ActivityItemAdapter;
import com.jerry.walking.module.activityPage.adapter.CategoryAdapter;
import com.jerry.walking.module.activityPage.bean.Category;
import com.jerry.walking.module.activityPage.bean.Lore;
import com.jerry.walking.module.activityPath.activity.SearchActivity;
import com.jerry.walking.utils.EventMessage;
import com.jerry.walking.utils.OkHttpUtils;
import com.jerry.walking.views.ExpandGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/5/9 0009.
 *
 *      活动主界面
 *
 */
public class ActivityHomeFragment extends BaseFragment{

    @BindView(R.id.pull_refer)
    PullToRefreshListView listView;
    @BindView(R.id.sp_city)
    Spinner spCity;
    private CategoryAdapter mAdapter;
    //分类信息
    private List<Category.CatsBean> mList;
    private ExpandGridView gridView;
    //列表信息
    private List<Lore.ActivitiesBean> mActivityList;
    private ActivityItemAdapter mActivityAdapter;

    private ArrayAdapter adapter;
    private List<String> list;
    //
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener =  new MyLocationListener();
    private String city;
    private int cityNum;

    @OnClick(R.id.iv_search_hot)
    void search(){
        Intent i = new Intent(getContext(),SearchActivity.class);
        startActivity(i);
    }
    @Override
    public void onDestroy() {
        mLocationClient.stop();
        super.onDestroy();
    }

    class MyLocationListener implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation location){
            String addCity = location.getCity();
            Log.e("address",addCity);
            EventBus.getDefault().post(new EventMessage(addCity,"city"));
        }
    }

    private int page_size = 20;
    @Override
    protected int getLayoutId(){
        return R.layout.fragment_home_activity;
    }


    @Override
    protected void initViews(){

        //百度地图
        mLocationClient = new LocationClient(getContext());     //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );
//        initSpinner();
        initLocation();
        mLocationClient.start();
        mActivityList = new ArrayList<>();

        mActivityAdapter = new ActivityItemAdapter(getContext(),mActivityList);
        listView.setAdapter(mActivityAdapter);
        initHeader();

        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>(){
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView){

                mActivityList.clear();
                page_size=20;
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView){

                page_size+=10;
                loadData();
            }

        });
    }

    private void initSpinner(){
        list = new ArrayList<>();
        list.add(city+" GPS");
        list.add("全国");
        list.add("北京市");
        list.add("上海市");
        list.add("广州市");
        spCity.setPrompt("出发地");
        adapter = new ArrayAdapter<>(getContext(),R.layout.spinner_item, R.id.textView1, list);
        spCity.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        spCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
//                Toast.makeText(getContext(), "你选择了：" + list.get(position), Toast.LENGTH_LONG).show();
                switch(position){

                    case 1:
                        initStartPlace();
                        break;
                    case 2:
                        cityNum = 2;
                        initStartPlace();
                        break;
                    case 3:
                        cityNum = 3;
                        initStartPlace();
                        break;
                    case 4:
                        cityNum = 326;
                        initStartPlace();
                        break;
                    default:
                        cityNum = 328;
                        initStartPlace();
                        break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent){}
        });
    }

    private void initStartPlace(){
        OkHttpUtils.get(Urls.ACTIVITY_START_PLACE+"&city="+cityNum, new OkHttpUtils.OnGetDataListener(){
            @Override
            public void onResponse(String url, String data){
                EventBus.getDefault().post(new EventMessage(data,url));
            }

            @Override
            public void onFailure(String url, String error){
            }
        });
    }

    //设置地图参数
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=0;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    private void initHeader(){

        gridView = (ExpandGridView) getLayoutInflater(new Bundle()).inflate(R.layout.fragment_activity_category,gridView,true);
        mList = new ArrayList<>();
        mAdapter = new CategoryAdapter(getContext(),mList);

        gridView.setAdapter(mAdapter);

        listView.getRefreshableView().addHeaderView(gridView);
        loadHeader();
    }

    private void loadHeader(){
        OkHttpUtils.get(Urls.HOME_CATEGORY, new OkHttpUtils.OnGetDataListener(){
            @Override
            public void onResponse(String url, String data){

                EventBus.getDefault().post(new EventMessage(data,url));
            }

            @Override
            public void onFailure(String url, String error){
            }
        });
    }

    @Override
    protected void loadData(){

        OkHttpUtils.get(Urls.CATEGORY_LIST+"&page_size="+page_size, new OkHttpUtils.OnGetDataListener(){
            @Override
            public void onResponse(String url, String data){

                EventBus.getDefault().post(new EventMessage(data,url));
            }

            @Override
            public void onFailure(String url, String error){
            }
        });
    }

    @Override
    protected void postEventResult(@NonNull EventMessage message){
        if(Urls.HOME_CATEGORY.equals(message.type)){
            Gson gson = new Gson();
            Category category = gson.fromJson(message.result, Category.class);
            if(category != null && category.getCats() != null){
                mList.addAll(category.getCats());
            }

            mAdapter.notifyDataSetChanged();
        }else if((Urls.CATEGORY_LIST+"&page_size="+page_size).equals(message.type)){
            Gson gson = new Gson();
            Lore lore = gson.fromJson(message.result, Lore.class);
            if(lore != null && lore.getActivities()!= null) {
                mActivityList.clear();
                mActivityList.addAll(lore.getActivities());

            }
            mActivityAdapter.notifyDataSetChanged();

        }else if("city".equals(message.type)){
            city = message.result;
            initSpinner();
        }else if((Urls.ACTIVITY_START_PLACE+"&city="+cityNum).equals(message.type)){
            Gson gson = new Gson();
            Lore lore = gson.fromJson(message.result, Lore.class);
            if(lore != null && lore.getActivities()!= null) {
                mActivityList.clear();
                mActivityList.addAll(lore.getActivities());
            }
            mActivityAdapter.notifyDataSetChanged();
        }
        listView.onRefreshComplete();
    }
}
